package com.polaris.live.ui.message.fragment.dialog

import android.graphics.Rect
import android.view.View
import android.view.View.OnAttachStateChangeListener
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import kotlin.math.abs

/**
 * 实现软键盘监听
 *
 * @author Created by lucas on 2023/10/28 15:48
 */
abstract class KeyboardBottomDialogFragment : BottomDialogFragment(),
    OnAttachStateChangeListener, OnGlobalLayoutListener {

    private val mRect = Rect()

    private var mIsSoftKeyboardShow = false
    private var mLastHeight = 0

    override fun onStart() {
        super.onStart()
        view?.addOnAttachStateChangeListener(this)
    }

    override fun onStop() {
        super.onStop()
        view?.removeOnAttachStateChangeListener(this)
    }

    override fun onViewAttachedToWindow(v: View) {
        v.viewTreeObserver.addOnGlobalLayoutListener(this)
    }

    override fun onViewDetachedFromWindow(v: View) {
        v.viewTreeObserver.removeOnGlobalLayoutListener(this)
    }

    override fun onGlobalLayout() {
        view?.getWindowVisibleDisplayFrame(mRect)

        val height = mRect.bottom - mRect.top
        if (mLastHeight != height && mLastHeight != 0) {
            val poorHeight = abs(mLastHeight - height)
            if (poorHeight >= KeyboardUtil.getMinKeyboardHeight(context)) {
                val isKeyboardShow = mLastHeight > height
                if (mIsSoftKeyboardShow != isKeyboardShow) {
                    mIsSoftKeyboardShow = isKeyboardShow
                    if (!isKeyboardShow) {
                        onHideKeyboard()
                    } else {
                        onShowKeyboard()
                    }
                }
            }
        }
        mLastHeight = height
    }

    protected abstract fun onShowKeyboard()

    protected abstract fun onHideKeyboard()

}